package com.iqik.sc.ns.service;

import com.iqik.sc.pojo.AuthCode;
import com.iqik.sc.ns.dao.AuthCodeRepository;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Calendar;
import java.util.Date;
import java.util.Optional;
import java.util.Random;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    /**
     * TODO 实现方法
     */

    private final AuthCodeRepository repository;

    @Autowired
    public AuthCodeServiceImpl(AuthCodeRepository repository) {
        this.repository = repository;
    }

    @Override
    public String createAuthCode(String email) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        Optional<AuthCode> result = repository.findOne(Example.of(authCode));
        if (!result.isEmpty()) {
            authCode = result.get();
        }
        String code = getCode();
        authCode.setCode(code);
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        authCode.setCreateTime(new Date(timeInMillis));
        authCode.setExpireTime(new Date(timeInMillis + 60 * 1000));
        System.out.println(authCode.toString());
        repository.save(authCode);
        return authCode.getCode();
    }

    @Override
    public int verityAuthCode(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Optional<AuthCode> result = repository.findOne(Example.of(authCode));
        if (result.isEmpty()) {
            return 1;
        }
        authCode = result.get();
        if (authCode.getExpireTime().after(new Date(Calendar.getInstance().getTimeInMillis()))) {
            return 0;
        }
        return 2;
    }

    private String[] numbers = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};

    private String getCode() {
        StringBuilder buf = null;
        Random random = new Random();
        int a = 0;
        while (a == 0) {
            a = random.nextInt(10);
        }
        buf = new StringBuilder(numbers[a]);
        for (int i = 0; i < 5; i++) {
            a = random.nextInt(10);
            buf.append(numbers[a]);
        }
        return buf.toString();
    }
}
